import os
import sys
import fnmatch
import threading
import time

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLineEdit, QWidget, QVBoxLayout, QFileDialog, \
    QMessageBox
from qt_material import apply_stylesheet

from ui import Ui_MainWindow

class RenametoolWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.show()
        self.setStyleSheet("""
                            QLabel {
                                font-size: 22px;
                                font-weight: bold;
                            }
                            QPushButton {
                                font-size:20px;
                            }
                            QListWidget{
                                font-size:16px;
                            }
                            QLineEdit{
                                font-size:22px;
                                color: #FFFFFF;
                            }
                            QCheckBox{
                                font-size:22px
                            }
                            QRadioButton{
                                font-size:22px
                            }
                            QComboBox{
                                font-size:20px;
                                color: #FFFFFF
                            }
                        """)

        self.msg_box = QMessageBox()
        self.ChooseVIdeoPath_pushButton.clicked.connect(self.ChooseVideoPath)
        self.ChooseSubtitlePath_pushButton.clicked.connect(self.ChooseSubtitlePath)

        self.StartProcess.clicked.connect(self.thread_rename)

        self.loading_progressBar.hide()
        self.loading_progressBar.setRange(0,0)
        self.progressBar.hide()
        self.progressBar.setRange(0, 100)
        self.progressBar.setFormat('Processing...  %p%'.format(self.progressBar.value()-self.progressBar.minimum()))

        self.season_list = list()
        for i in range(100):
            self.season_list.append(f"第{i}季")
        self.select_season.addItems(self.season_list)
        self.select_season.setCurrentIndex(1)
        self.refresh_button.clicked.connect(self.LoadLanguage)

    # 选择视频路径按钮对应函数
    def ChooseVideoPath(self):
        m = QFileDialog.getExistingDirectory(None, "选取文件夹")
        if m == '':
            return
        self.VideoPath_lineEdit.setText(m)

    # 选择字幕路径按钮对应函数
    def ChooseSubtitlePath(self):
        m = QFileDialog.getExistingDirectory(None, "选取文件夹")
        if m == '':
            return
        self.SubtitlePath_lineEdit.setText(m)
        self.LoadLanguage()

    def LoadLanguage(self):
        folder_path = self.SubtitlePath_lineEdit.text()
        if not os.path.exists(folder_path):
            self.msg_box.warning(self, 'warning', '字幕路径不存在')
            return

        file_extensions = (".ass", ".srt", ".ssa")  # 支持的文件扩展名
        supported_language = ['zh', 'chs', 'cht', 'eng', 'jpn']
        SubtitleLanguages = set()  # 用于存储提取的语言
        for filename in os.listdir(folder_path):
            if filename.endswith(file_extensions):
                SubtitleLanguages.add(filename.split(".")[-2]) # 提取倒数第二个点之间的部分作为语言
        self.ChooseLanguage_comboBox.clear()
        supported_lang_list = set()
        if len(SubtitleLanguages) !=0:
            for lang in SubtitleLanguages:
                if lang in supported_language:
                    supported_lang_list.add(lang)
                else:
                    self.msg_box.warning(self, "注意！", f"无法识别语言{lang}，但可以继续重命名！")
        else:
            self.msg_box.warning(self,"注意！",  "当前目录下没有找到字幕文件！")
        self.ChooseLanguage_comboBox.addItems(list(supported_lang_list))

    def check(self):
        if self.VideoPath_lineEdit.text() == '':
            self.msg_box.critical(self, '错误！', '没有设置视频路径')
            return False

        if self.SubtitlePath_lineEdit.text() == '':
            self.msg_box.critical(self, '错误！', '没有设置字幕路径')
            return False

        if self.NewName_lineEdit.text() == '':
            self.msg_box.critical(self, '错误！', '没有设置新文件名')
            return False

        return True

    def thread_rename(self):
        threading.Thread(target=self.Rename).start()


    def Rename(self):
        self.loading_progressBar.show()
        self.progressBar.reset()
        self.progressBar.show()
        if not self.check():
            self.reset_progressbar()
            return
        Subtitle_file_list = os.listdir(self.SubtitlePath_lineEdit.text())
        Video_file_list = os.listdir(self.VideoPath_lineEdit.text())
        Video_file_list.sort()
        first_file_list = []

        # 第一次 按语言筛选
        try:
            if self.ChooseLanguage_comboBox.currentText() != '':
                for _, filename in enumerate(Subtitle_file_list):
                    if filename.split(".")[-2] == self.ChooseLanguage_comboBox.currentText():
                        first_file_list.append(filename)
            else:
                first_file_list = Subtitle_file_list
        except:
            self.msg_box.critical(self, 'error', '按语言筛选时出错')
            self.reset_progressbar()
        self.progressBar.setValue(33)

        first_file_list.sort()

        # 第二次按文件名筛选
        try:
            matching = self.NameMatching_lineEdit.text()
            if matching != '':
                matching = matching.replace('[','?').replace(']','?')
                second_file_list = []
                for _, filename in enumerate(first_file_list):
                    if fnmatch.fnmatch(filename, matching):
                        second_file_list.append(filename)
                if len(second_file_list) == 0:
                    self.msg_box.critical(self, 'error', '名称匹配失败！')
                    return

                for index, filename in enumerate(second_file_list):
                    old_path = os.path.join(self.SubtitlePath_lineEdit.text(), filename)
                    new_filename = f"{self.NewName_lineEdit.text()}-S{self.select_season.currentIndex():02d}E{index + 1:02d}-第{index + 1}集.{self.ChooseLanguage_comboBox.currentText()}.{filename.split('.')[-1]}"
                    new_path = os.path.join(self.VideoPath_lineEdit.text(), new_filename)
                    os.rename(old_path, new_path)

            else:
                for index, filename in enumerate(first_file_list):
                    old_path = os.path.join(self.SubtitlePath_lineEdit.text(), filename)
                    new_filename = f"{self.NewName_lineEdit.text()}-S{self.select_season.currentIndex():02d}E{index + 1:02d}-第{index + 1}集.{self.ChooseLanguage_comboBox.currentText()}.{filename.split('.')[-1]}"
                    new_path = os.path.join(self.VideoPath_lineEdit.text(), new_filename)
                    os.rename(old_path, new_path)
        except:
            self.msg_box.critical(self, 'error', '按文件名筛选时出错')
            self.reset_progressbar()
        self.progressBar.setValue(67)

        try:
            for index, filename in enumerate(Video_file_list):
                old_path = os.path.join(self.VideoPath_lineEdit.text(), filename)
                new_filename = f"{self.NewName_lineEdit.text()}-S{self.select_season.currentIndex():02d}E{index + 1:02d}-第{index + 1}集.{self.ChooseLanguage_comboBox.currentText()}.{filename.split('.')[-1]}"
                new_path = os.path.join(self.VideoPath_lineEdit.text(), new_filename)
                os.rename(old_path, new_path)
        except:
            self.msg_box.critical(self, 'error', '重命名视频文件时出错')
            self.reset_progressbar()
        self.progressBar.setValue(100)

        self.msg_box.about(self, '成功！', '重命名成功')
        self.reset_progressbar()
        if self.open_output_dir_Checkbox.isChecked():
            os.startfile(self.VideoPath_lineEdit.text())

    def reset_progressbar(self):
        self.progressBar.hide()
        self.loading_progressBar.hide()

if __name__== "__main__":
    app = QApplication(sys.argv)
    apply_stylesheet(app, theme='dark_teal.xml')
    window = RenametoolWindow()
    sys.exit(app.exec_())